package com.rongshu.view.home.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.rongshu.R;
import com.rongshu.utils.DateUtils;
import com.rongshu.view.home.entity.AiteListBean;
import com.rongshu.view.home.entity.CommentDetails;
import com.rongshu.view.home.entity.CommentReplysBean;
import com.rongshu.view.home.listener.OnCommentItemFunctionClickListener;
import com.rongshu.view.home.listener.OnExpandFunctionListener;
import com.rongshu.view.home.widget.CommentExpandableLinearLayout;
import com.rongshu.view.home.widget.ExpandableTextView;
import com.rongshu.widget.SmartLoadingView;
import com.widget.CircleImageView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ArticleCommentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    // 普通布局
    private final int TYPE_ITEM = 1;
    // 脚布局
    private final int TYPE_FOOTER = 2;
    // 当前加载状态，默认为加载完成
    private int loadState = 1;
    // 正在加载
    public final int LOADING = 1;
    // 加载完成
    public final int LOADING_COMPLETE = 2;
    // 加载到底
    public final int LOADING_END = 3;
    // 空数据
    public final int LOADING_EMPTY = 4;


    private Context mContext = null;
    private List<CommentDetails.ResponseBean> responseBeanList = null;
    //interface
    private OnCommentItemFunctionClickListener mOnItemFunctionClickListener = null;
    //局部刷新
    //回复评论界面收起状态修改
    public final int SHRINK = 0x01;
    //点赞
    public final int GIVELIKE = 0x02;


    public ArticleCommentAdapter(Context context) {
        this.mContext = context;
    }

    public void setResponseBeanList(List<CommentDetails.ResponseBean> list) {
        this.responseBeanList = list;
    }

    public void addResponseBeanList(List<CommentDetails.ResponseBean> list) {
        this.responseBeanList.addAll(list);
    }

    public List<CommentDetails.ResponseBean> getResponseBeanList() {
        return responseBeanList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_comment_item_view, parent, false);
            return new CommentViewHolder(view);
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_refresh_footer, parent, false);
            return new FootViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof CommentViewHolder) {
            final CommentDetails.ResponseBean responseBean = responseBeanList.get(position);
            final CommentViewHolder viewHolder = (CommentViewHolder) holder;
            try {
                //第一个评论者头像
                RequestOptions options = new RequestOptions()
                        .placeholder(R.drawable.user_head_icon);
                Glide.with(mContext)
                        .load(responseBean.getAvatar())
                        .apply(options)
                        .into(viewHolder.iv_head_icon);
                //vip
                viewHolder.iv_vip.setVisibility(responseBean.isVip() ? View.VISIBLE : View.GONE);
                //bi_name
                viewHolder.txt_article_title.setText(responseBean.getBi_name());
                //data
                String time = responseBean.getCreate_datetime();
                viewHolder.txt_article_data.setText(DateUtils.ConvertDate(time));
                //like count
                int likeCount = responseBean.getLikeCount();
                int islike = responseBean.getIslike();
                viewHolder.txt_like_count.setVisibility(likeCount == 0 ? View.GONE : View.VISIBLE);
                viewHolder.txt_like_count.setText(likeCount == 0 ? "" : responseBean.getLikeCount() + "");
                //like
                viewHolder.iv_like.setImageResource(islike == 0 ? R.drawable.give_like_white_icon : R.drawable.give_like_yellow_icon);
                //content
                String content = responseBean.getContents();
                content = content.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                content = URLDecoder.decode(content, "utf-8");
                final String finalContent = content;
                if (!TextUtils.isEmpty(content)) {
                    //atlist
                    final List<AiteListBean> aiteListBean = responseBean.getAiteList();
                    viewHolder.txt_article_content.setAiteListBeanList(aiteListBean);
                    viewHolder.txt_article_content.setText(content);
                    viewHolder.txt_article_content.setOnExpandFunctionListener(new OnExpandFunctionListener() {
                        @Override
                        public void onClick() {
                            if (mOnItemFunctionClickListener != null) {
                                mOnItemFunctionClickListener.onItemClickListener(viewHolder.itemView,
                                        position, finalContent, responseBean.getBi_name(), responseBean.getId(), responseBean.getFrom_uid());
                            }
                        }

                        @Override
                        public void onAtClick(int user_id) {
                            if (mOnItemFunctionClickListener != null) {
                                mOnItemFunctionClickListener.onItemHeaderClickListener(user_id, (responseBean.getIs_allow_browse_homepage() == 1));
                            }
                        }
                    });
                }
                final int count = responseBean.getComment_replyCount();
                final boolean isExpand = responseBean.isExpand();
                List<CommentReplysBean> replysBeans = responseBean.getComment_replys();
                //reply
                if (count > 0 && replysBeans != null && !replysBeans.isEmpty()) {
                    viewHolder.commentExpandableLinearLayout.setVisibility(View.VISIBLE);
                    viewHolder.commentExpandableLinearLayout.setIsExpand(isExpand);
                    viewHolder.commentExpandableLinearLayout.setCommentReplysBeanList(responseBean.getComment_replys(), count);
                } else {
                    viewHolder.commentExpandableLinearLayout.setVisibility(View.GONE);
                }
                //设置展开字体
                if (count > 1 && !isExpand) {
                    viewHolder.commentExpandableLinearLayout.setExpandText("展开" + (count - 1) + "条回复");
                } else {
                    viewHolder.commentExpandableLinearLayout.setExpandText("收起");
                }
                //展开点击
                viewHolder.commentExpandableLinearLayout.setOnStateChangeListener(new CommentExpandableLinearLayout.OnStateChangeListener() {
                    @Override
                    public void onStateChanged(boolean isExpanded) {
                        responseBean.setExpand(isExpanded);
                        if (isExpanded) {
                            if (mOnItemFunctionClickListener != null) {
                                mOnItemFunctionClickListener.onItemExpandClickListener(isExpanded,
                                        responseBean.getComment_replyCount(), responseBean.getId(), position);
                            }
                        } else {
                            notifyItemRangeChanged(position, 1, SHRINK);
                        }
                    }
                });
                //二级评论点击
                viewHolder.commentExpandableLinearLayout.setOnItemClickListener(new CommentExpandableLinearLayout.OnItemClickListener() {
                    @Override
                    public void onItemClick(int replyPosition) {
                        if (mOnItemFunctionClickListener != null) {
                            CommentReplysBean bean = responseBean.getComment_replys().get(replyPosition);
                            //评论内容
                            String content = null;
                            content = bean.getContents();
                            content = content.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                            try {
                                content = URLDecoder.decode(content, "utf-8");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            //评论commentid
                            int comment_id = responseBean.getId();
                            //评论评论reply_id
                            int reply_id = bean.getId();
                            //对谁评论的评论者姓名
                            String bi_name = bean.getFrom_Name();
                            //对谁评论的评论者id
                            int reply_user_id = bean.getFrom_uid();
                            if (mOnItemFunctionClickListener != null) {
                                mOnItemFunctionClickListener.onItemChildClickListener(viewHolder.commentExpandableLinearLayout.getChildAt(replyPosition),
                                        position, replyPosition, content, bi_name, comment_id, reply_id, reply_user_id);
                            }
                        }
                    }

                    //二级评论@和头像点击
                    @Override
                    public void onItemAtAndHeaderClick(int user_id, boolean is_allow_browse_homepage) {
                        if (mOnItemFunctionClickListener != null) {
                            mOnItemFunctionClickListener.onItemHeaderClickListener(user_id, is_allow_browse_homepage);
                        }
                    }
                });

                //头像点击
                viewHolder.layout_head.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mOnItemFunctionClickListener != null) {
                            mOnItemFunctionClickListener.onItemHeaderClickListener(responseBean.getFrom_uid(), (responseBean.getIs_allow_browse_homepage() == 1));
                        }
                    }
                });

                //点赞点击
                viewHolder.layout_like.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mOnItemFunctionClickListener != null) {
                            mOnItemFunctionClickListener.onItemGiveLikeClickListener(responseBean.getId(), position);
                        }
                    }
                });
                //复制，回复，删除功能
                viewHolder.layout_all.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mOnItemFunctionClickListener != null) {
                            mOnItemFunctionClickListener.onItemClickListener(viewHolder.itemView,
                                    position, finalContent, responseBean.getBi_name(), responseBean.getId(), responseBean.getFrom_uid());
                        }
                    }
                });
            } catch (
                    UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else if (holder instanceof FootViewHolder) {
            FootViewHolder footViewHolder = (FootViewHolder) holder;
            switch (loadState) {
                case LOADING: // 正在加载
                    footViewHolder.loadingProgress.setVisibility(View.VISIBLE);
                    footViewHolder.loadingMsg.setVisibility(View.VISIBLE);
                    footViewHolder.loadingMsg.setText("加载中...");
                    footViewHolder.loadingProgress.start();
                    break;

                case LOADING_COMPLETE: // 加载完成
                    footViewHolder.loadingProgress.stop();
                    footViewHolder.loadingProgress.setVisibility(View.INVISIBLE);
                    footViewHolder.loadingMsg.setVisibility(View.VISIBLE);
                    footViewHolder.loadingMsg.setText("加载完成");
                    break;

                case LOADING_END: // 加载到底
                    footViewHolder.loadingProgress.stop();
                    footViewHolder.loadingProgress.setVisibility(View.GONE);
                    footViewHolder.loadingMsg.setVisibility(View.VISIBLE);
                    footViewHolder.loadingMsg.setText("--没有更多了--");
                    break;
                case LOADING_EMPTY: // 空数据
                    footViewHolder.loadingProgress.setVisibility(View.GONE);
                    footViewHolder.loadingMsg.setVisibility(View.GONE);
                    footViewHolder.loadingProgress.stop();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List<Object> payloads) {
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position);
        } else {
            //viewholder
            CommentViewHolder viewHolder = (CommentViewHolder) holder;
            //CommentDetails
            final CommentDetails.ResponseBean responseBean = responseBeanList.get(position);
            //获取局部刷新标识
            int payload = (int) payloads.get(0);
            switch (payload) {
                case GIVELIKE://点赞
                    //like count
                    int likeCount = responseBean.getLikeCount();
                    int islike = responseBean.getIslike();
                    viewHolder.txt_like_count.setVisibility(likeCount == 0 ? View.GONE : View.VISIBLE);
                    viewHolder.txt_like_count.setText(likeCount == 0 ? "" : responseBean.getLikeCount() + "");
                    //like
                    viewHolder.iv_like.setImageResource(islike == 0 ? R.drawable.give_like_white_icon : R.drawable.give_like_yellow_icon);
                    break;
                case SHRINK://收起状态改变
                    final int count = responseBean.getComment_replyCount();
                    final boolean isExpand = responseBean.isExpand();
                    viewHolder.commentExpandableLinearLayout.setIsExpand(isExpand);
                    //设置展开字体
                    if (count > 1 && !isExpand) {
                        viewHolder.commentExpandableLinearLayout.setExpandText("展开" + (count - 1) + "条回复");
                    } else {
                        viewHolder.commentExpandableLinearLayout.setExpandText("收起");
                    }
                    break;
            }
        }
    }

    /**
     * 设置上拉加载状态
     *
     * @param loadState 0.正在加载 1.加载完成 2.加载到底
     */
    public void setLoadState(int loadState) {
        this.loadState = loadState;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return responseBeanList == null ? 1 : responseBeanList.size() + 1;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        // 最后一个item设置为FooterView
        if (position + 1 == getItemCount()) {
            return TYPE_FOOTER;
        } else {
            return TYPE_ITEM;
        }
    }

    public class CommentViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.layout_all)
        RelativeLayout layout_all;
        @BindView(R.id.layout_head_icon)
        RelativeLayout layout_head;
        @BindView(R.id.iv_head_icon)
        CircleImageView iv_head_icon;
        @BindView(R.id.iv_vip)
        ImageView iv_vip;
        @BindView(R.id.iv_like)
        ImageView iv_like;
        @BindView(R.id.txt_article_title)
        TextView txt_article_title;
        @BindView(R.id.txt_article_data)
        TextView txt_article_data;
        @BindView(R.id.txt_like_count)
        TextView txt_like_count;
        @BindView(R.id.layout_like)
        LinearLayout layout_like;
        @BindView(R.id.txt_article_content)
        ExpandableTextView txt_article_content;
        @BindView(R.id.commentLiearLayout)
        CommentExpandableLinearLayout commentExpandableLinearLayout;

        public CommentViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

    }

    private class FootViewHolder extends RecyclerView.ViewHolder {

        SmartLoadingView loadingProgress;
        TextView loadingMsg;

        FootViewHolder(View itemView) {
            super(itemView);
            loadingProgress = itemView.findViewById(R.id.pb_loading);
            loadingMsg = itemView.findViewById(R.id.tv_loading);
        }
    }

    /**
     * set listener
     */
    public void setOnItemFunctionClickListener(OnCommentItemFunctionClickListener listener) {
        this.mOnItemFunctionClickListener = listener;
    }
}
